#include "Game.h"

Game::Game()
{
}

int Game::random(int a, int b)
{
    return rand()%(b-a) +a;
}

void Game::init()
{
	srand(time(NULL));
	m_app.create(sf::VideoMode(512, 360, 32), "Dream-Space Prototype", sf::Style::Close);
	m_app.setFramerateLimit(60);
	m_view = m_app.getDefaultView();
	m_focus = false;
	m_fontFocus.loadFromFile("ressources/font.ttf");

	m_imageManager.setImage("ressources/ressources.png", 16, sf::Color::Color(255, 81, 243));

	m_level.init(&m_imageManager);
	m_level.loadLevel("ressources/level.png");
	m_level.addUnit(new WorkerUnit(), sf::Vector2f(200, 200), 1);

	m_textFocus.setString("Game paused !");
	m_textFocus.setFont(m_fontFocus);
	m_textFocus.setCharacterSize(52);
	m_textFocus.setColor(sf::Color::Blue);

	m_hud.init(&m_imageManager);

	m_ressourceMgr.init();
}

void Game::maj()
{
	float posViewX = m_view.getCenter().x - m_view.getSize().x / 2;
	float posViewY = m_view.getCenter().y - m_view.getSize().y / 2;
	while(m_app.pollEvent(m_event))
	{
		if(m_event.type == sf::Event::Closed)
			m_app.close();
		if(m_event.type == sf::Event::GainedFocus)
			m_focus = false;
		if(m_event.type == sf::Event::LostFocus)
			m_focus = true;
	}
	if(m_focus)
		m_textFocus.setPosition(m_view.getCenter().x - m_textFocus.getGlobalBounds().width / 2, m_view.getCenter().y - m_textFocus.getGlobalBounds().height / 2);

	m_app.setView(m_view);
	if(!m_focus)
		m_level.maj(&m_ressourceMgr);

	if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
		if(posViewY + m_view.getSize().y < m_level.m_height)
			m_view.move(0, 4);
	if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
		if(posViewY > 0)
			m_view.move(0, -4);
	if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
		if(posViewX + m_view.getSize().x < m_level.m_width)
			m_view.move(4, 0);
	if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
		if(posViewX > 0)
			m_view.move(-4, 0);
	m_hud.maj(&m_view, &m_ressourceMgr);
	m_ressourceMgr.maj(&m_level);
}

void Game::render()
{
	while(m_app.isOpen())
	{
		maj();
		m_app.clear(sf::Color::Black);
		m_level.render(&m_app, &m_view);
		m_hud.render(&m_app);
		m_ressourceMgr.maj(&m_level);
		
		if(m_focus)
			m_app.draw(m_textFocus);
		m_app.display();
	}
}